package com.itheima.reggie.service.impl;

import com.itheima.reggie.dao.ShoppingCartDao;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartDao shoppingCartDao;
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        ShoppingCart cart = shoppingCartDao.findCartItem(shoppingCart);
        if (cart != null) {
            cart.setNumber(cart.getNumber()+1);
            shoppingCartDao.updatNumber(cart);
        }else {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            cart = shoppingCart;
            shoppingCartDao.add(cart);
        }
        return cart;
    }
    @Override
    public ShoppingCart subNumber(ShoppingCart shoppingCart) {
        ShoppingCart cart = shoppingCartDao.findCartItem(shoppingCart);
        if (cart.getNumber()>=1) {
            cart.setNumber(cart.getNumber()-1);
            shoppingCartDao.subNumber(cart);
            return cart;
        }else {
            cart.setNumber(0);
            return cart;
        }
    }

    @Override
    public List<ShoppingCart> findCartItemByUserId(Long userId) {
        return shoppingCartDao.findCartItemByUserId(userId);
    }

    @Override
    public void deleteCartItemByUserId(Long userId) {
        shoppingCartDao.deleteCartItemByUserId(userId);
    }
}
